<template>
  <div class="inside-comment">
    <el-tabs v-model="activeTab" size="large">
      <el-tab-pane label="课程总评" name="totalRate" class="rate-tab">
        <div class="rating-container" v-if="Object.keys(totalRateDetailData).length > 0">
          <!-- 课程总评 -->
          <div class="total-rate card">
            <div class="rate-header">
              <h3 class="rate-title">课程总评</h3>
              <div class="overall-rating">
                <el-rate 
                  v-model="totalRateDetailData.avgRating" 
                  disabled 
                  :show-score="true"
                  score-template="{value} 分">
                </el-rate>
              </div>
            </div>
            
            <div class="rate-detail">
              <div class="rate-item">
                <span class="item-title">平均评分</span>
                <span class="item-value highlight">{{ totalRateDetailData.avgRating || '0.0' }}</span>
              </div>
              <div class="rate-item">
                <span class="item-title">评分人数</span>
                <span class="item-value highlight">{{ totalRateDetailData.total || 0 }}人</span>
              </div>
              <div class="star-distribution">
                <div v-for="(count, star) in totalRateDetailData.starCounts" :key="star" class="star-row">
                  <el-tag size="small" :type="getStarTagType(star)">{{ star }}星</el-tag>
                  <!-- <el-progress 
                    :percentage="(count / totalRateDetailData.total) * 100" 
                    :show-text="false"
                    :stroke-width="12"
                    :color="getStarColor(star)">
                  </el-progress> -->
                  <span class="star-count">{{ count }}人</span>
                </div>
              </div>
            </div>
          </div>
        
          <!-- 课程各期评价 -->
          <div class="instance-rate card">
            <h3 class="rate-title">课程各期评价</h3>
            <div class="rate-list" v-if="totalRateDetailData.courseInstanceRatingDistributions && totalRateDetailData.courseInstanceRatingDistributions.length > 0">
              <div v-for="instance in totalRateDetailData.courseInstanceRatingDistributions" :key="instance.courseInstanceId" class="instance-card">
                <div class="instance-header">
                  <span class="instance-id">期次： {{ instance.courseInstanceName }}</span>
                  <el-rate
                    v-model="instance.avgRating"
                    disabled
                    :show-score="true"
                    score-template="{value} 分">
                  </el-rate>
                </div>
                
                <div class="instance-detail">
                  <div class="detail-item">
                    <span>平均分：</span>
                    <span class="highlight">{{ instance.avgRating?.toFixed(1) }}</span>
                  </div>
                  <div class="detail-item">
                    <span>评分人数：</span>
                    <span class="highlight">{{ instance.total }}人</span>
                  </div>
                </div>
                
                <div class="star-distribution">
                  <div v-for="(count, star) in instance.starCounts" :key="star" class="mini-star-row">
                    <el-tag size="small" :type="getStarTagType(star)">{{ star }}星</el-tag>
                    <span class="mini-count">{{ count }}人</span>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无数据" />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="评价管理" name="rateManage" class="rate-tab">
        <!-- 课程评价内容 -->
        <div class="top-total">
          <div class="left-rate" v-if="rateData && rateData.length > 0">
            <div class="num">{{totalRateData.avgRating}}</div>
            <div class="rate">
              <el-rate
                v-model="totalRateData.avgRating"
                disabled
                text-color="#ff9900"
              />
              <p>共{{totalRateData.total}}条评价</p>
            </div>
          </div>
          <div class="no-total-rate" v-else>暂无总评</div>
          <div class="right-box">
            <div class="right-condition">
              <span @click="changeCondition('all')" :class="{'selected' : checkCondition == 'all'}">全部</span>
              <span @click="changeCondition('now')" :class="{'selected' : checkCondition == 'now'}">各期</span>
            </div>
            <el-select v-model="curseInstance" placeholder="选择课程状态" style="width: 120px;margin-left: 20px;" :disabled="checkCondition == 'all'" @change="changeCurseInstance">
              <el-option
                v-for="item in instanceList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <!-- 评价分页 -->
        <div class="rate-list" v-if="rateData && rateData.length > 0">
          <div class="rate-item" v-for="item in rateData" :key="item.id">
            <div class="left-avtor">
              <img v-if="item.scaledUrl" :src="item.scaledUrl" alt="">
              <!-- <img v-else src="" alt=""> -->
            </div>
            <div class="right-info">
              <div class="top">
                <div class="left-info">
                  <div class="username">{{item?.userInfo?.name}}</div>
                  <el-rate
                    v-model="item.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value} 分"
                  />
                </div>
                <div class="right-toption">
                  <el-icon type="danger" @click="delRate(item)" class="del-icon"><Delete /></el-icon>
                </div>
              </div>
              <div class="rate-content">{{item.content}}</div>
              <div class="time">{{ item.createdAt }}<p>{{item.courseInstanceName}}</p></div>
            </div>
          </div>
          <PaginationView
            :isAffix = "false"
            :total="queryData.total"
            :pageSize="queryData.pageSize"
            :currentPage="queryData.currentPage"
            :allChoose="isAllChooseBtn"
            :pageChoose="isPageChooseBtn"
            :options="batchOptions"
            :checkedNum="checkedNum"
            :canChoose="queryData.total > 0"
            @changeSize="handleSizeChange"
            @currentChange="handleCurrentChange"
            @changePageChoose="handlePageChoose"
            @changeAllChoose="handleAllChoose"
            @invertChoose="handleInvertChoose"
            @checkOption="handleBatchOptions"
            @refreshList="handleGetFormManageList"
            @cancelChoose="handleResetPagination"
            v-if="tableData.length > 0"
          />
        </div>
        <el-empty v-else description="暂无数据" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted  } from 'vue'
import { 
  ratingItemPaging,
  getCourseRatingDetail,
  getCourseInstanceRating,
  deleteRatingItem
 } from "@/api/rate";
import { tableList as mixTable } from '@ruifox-cms/utils'
import { scaledAndCrop } from '@/api/file'
import { selectPageInstance } from '@/api/instance'
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete } from '@element-plus/icons-vue'

const props = defineProps({
  courseId: {
    type: String,
    default: ''
  },
})
const activeTab = ref("totalRate")
let abortController = new AbortController()
const totalRateDetailData = ref({})
const getTotalRateData = async () => {
  try {
    const res = await getCourseRatingDetail({courseId: props.courseId})
    if (res.code === 20000) {
      totalRateDetailData.value = res.data
      console.log("totalRateDetailData", totalRateDetailData.value);
      
    } 
  } catch (e) {
    if (e.name !== 'AbortError') {
      console.error(e)
    }
  }
}

const getStarTagType = (star) => {
  const types = {
    '1': 'danger',
    '2': 'warning',
    '3': 'info',
    '4': 'success',
    '5': 'success'
  }
  return types[star] || 'info'
}

//********获取评价
const {
  queryData,
  tableData,
  // tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  // getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  // handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: ratingItemPaging,
});
const defaultQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total:10,
  courseId: props.courseId,
  courseInstanceId: "",
  userId:"",
});
Object.assign(queryData, defaultQuery);
const rateData = ref([])
const curseInstance = ref('') //当前课程实例

//获取评分数据后，裁剪重新获取头像图片
const processRateData = async () => {
  rateData.value = await Promise.all(rateData.value.map(async item => {
    try {
      const res = await scaledAndCrop({
        cropHeight: 80,
        cropWidth: 80,
        startX: null,
        startY: null,
        url: item.userInfo.avatar,
      });
      return {
        ...item,
        scaledUrl: res.code === 20000 ? res.data : item.userInfo.avatar
      };
    } catch (error) {
      return {
        ...item,
        scaledUrl: item.userInfo.avatar
      };
    }
  }));
};
const checkCondition = ref('all')

//获取评分数据
const handleGetFormManageList = async () => { 
  //按课程实例是否为空判断当前是查全部还是当前实例
  if(checkCondition.value == 'all'){
    queryData.courseInstanceId = "";
    getCourseRate()
  } else if(checkCondition.value == 'now'){
    queryData.courseInstanceId = curseInstance.value;
    getCourseInstanceRate()
  }
  let res = await ratingItemPaging(queryData)
  if(res.code == 20000){
    rateData.value = res.data.list;
    console.log("评分数据", rateData.value);
  }
  processRateData();
};  

//删除评价
const delRate = async (item) => {
  await ElMessageBox.confirm('此操作将永久删除该评价, 是否继续?', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  const res = await deleteRatingItem({courseRatingItemId: item.id});
  if(res.code == 20000){
    ElMessage.success("删除成功");
    await handleGetFormManageList();
  } 
}
//全部评价和当前课程实例评价切换
const changeCondition = async (condition) => {
  checkCondition.value = condition;
  await handleGetFormManageList()
}
const totalRateData = ref({
  avgRating: 0,
  total: 0
})

//获取课程总评分
const getCourseRate = async () => {
  const res = await getCourseRatingDetail({courseId: props.courseId});
  if(res.code == 20000){
    totalRateData.value.avgRating = res.data.avgRating
    totalRateData.value.total = res.data.total
    console.log("总评价数据", totalRateData.value);
    
  }
}

//获取课程实例总评分
const getCourseInstanceRate = async () => {
  const res = await getCourseInstanceRating({courseInstanceId: curseInstance.value});
  if(res.code == 20000){
    totalRateData.value.avgRating = res.data.avgRating
    totalRateData.value.total = res.data.ratingCount
    console.log("当前实例评价数据", totalRateData.value);

  }
}

//获取当前课程实例
const instanceList = ref([])
const getInstanceList = async () => {
  const res = await selectPageInstance({
    courseIds: [props.courseId],
    currentPage: 1,
    pageSize: 100,
    scheduleIds: [],
    principalIds: [],
    startTime: "",
    endTime: "",
    finish: ""
  });
  if (res.code === 20000) {
    instanceList.value = res.data.list;
    if (instanceList.value.length > 0) {
      curseInstance.value = instanceList.value[0].id; // 默认选择第一个实例
      queryData.courseInstanceId = curseInstance.value;
      await handleGetFormManageList();
    }
  }
}
const changeCurseInstance = async () => {
  await handleGetFormManageList();
}
onMounted(async () => {
  await getTotalRateData()
  await getInstanceList()
})
onUnmounted(() => {
  abortController.abort()
})
</script>

<style scoped lang="scss">
.rating-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  .card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  .rate-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    .rate-title {
      font-size: 18px;
      font-weight: 600;
      color: $black;
    }
  }
  .rate-detail {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;

    .rate-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 12px;
      background: #f5f7fa;
      border-radius: 4px;
    }

    .highlight {
      font-weight: bold;
      color: #409eff;
      font-size: 16px;
    }

    .star-distribution {
      grid-column: span 2;
      /* margin-top: 10px; */
      display: flex;
      flex-wrap: wrap;
      .star-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        width: max-content;
        padding-right: 10px;
        .star-label {
          width: 30px;
          color: #606266;
        }
        .star-count {
          width: 50px;
          /* text-align: right; */
          color: #909399;
        }
      }
    }
  }
  .instance-rate {
    .rate-title {
      font-size: 18px;
      font-weight: 600;
      color: $black;
    }
    .rate-list{
      margin-top: 20px;
    }
    .instance-card {
      padding: 12px;
      margin-bottom: 12px;
      border: 1px solid #ebeef5;
      border-radius: 6px;
      .instance-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .instance-id {
          color: #909399;
          font-size: 13px;
        }
      }
      .instance-detail {
        display: flex;
        gap: 20px;
        margin: 10px 0;
      }
      .mini-star-row {
        display: inline-flex;
        align-items: center;
        margin-right: 12px;
        margin-bottom: 8px;

        .mini-count {
          margin-left: 5px;
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }
}
.rate-tab{
  padding: 10px;
  box-sizing: border-box;
}
/* 评分显示 */
.top-total{
  display: flex;
  align-items: center;
  justify-content: space-between;
  .left-rate{
    display: flex;
    align-items: center;
    .num{
      line-height: px2rem(64);
      font-size: px2rem(48);
      width: px2rem(72);
      color: #FF7A3E;
      font-weight: bold;
    }
    .rate{
      margin-left: px2rem(10);
      .el-rate{
        height: auto;
      }
      :deep(.el-rate__text){
        display: none;
      }
      p{
        font-size: px2rem(14);
        color: #999999;
      }
    }
  }
  .no-total-rate{
    font-size: px2rem(24);
    color: $black
  }
  .right-box{
    display: flex;
    align-items: center;
    .right-condition{
      text-align: center;
      display: inline-block;
      padding: px2rem(6) px2rem(15);
      border: 1px solid #ededed;
      color: #999999;
      font-size: px2rem(14);
      span{
        border-right: 1px solid #E6E6E6;
        padding-right:  px2rem(12);
        cursor: pointer;
        font-size: px2rem(18);
        &:last-child{
          padding-right:  0;
          padding-left:  px2rem(12);
          border-right: none;
        }
        &.selected{
          color: $mainColor;
        }
      }
    }
    .add-rate-but{
      margin-left: px2rem(20);
    }
  }
}
.rate-list{
  margin-top: px2rem(20);
  .rate-item{
    padding: px2rem(15) 0;
    border-bottom: 1px solid $borderColor;
    display: flex;
    .left-avtor{
      width: px2rem(45);
      height: px2rem(45);
      box-shadow: 0 0 5px rgba(black,.1);
      border-radius: 50%;
      img{
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
      }
    }
    .right-info{
      margin-left: px2rem(20);
      flex: 1;
      .top{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .username{
          font-size: px2rem(16);
          margin-right: px2rem(10);
          color: $black_2;
        }
        .el-rate{
          height: auto;
        }
        .del-icon{
          font-size: 18px;
          color: $partyColor;
          cursor: pointer;
        }
      }
      .rate-content{
        font-size: px2rem(18);
        line-height: 1.5;
        margin-top: px2rem(10);
        color: $black;
      }
      .time{
        margin-top: px2rem(10);
        display: flex;
        color: #666;
        align-items: center;
        font-size: px2rem(16);
        line-height: px2rem(16);
        p{
          margin-left: px2rem(10);
        }
        span{
          margin-left: px2rem(5);
        }
      }
    }
  }
}
.ruifox-table-new-no-data{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  width: 100%;
  height: 80px;
  border-bottom: 1px #e3e4e6 solid;
  svg{
    flex-shrink: 0;
    path{
      fill: #AAAAAA;
    }
  }
  &>i{
    font-size: 80px;
    color: #AAAAAA;
  }
  &>span{
    font-size: 12px;
    color: #AAAAAA;
  }
}
</style>
